package com.xq.tmall.agu.job.impl;

import com.xq.tmall.agu.ferign.StockSectorSpider;
import com.xq.tmall.agu.job.AbstractTimeJob;
import com.xq.tmall.container.SimpleTimerJobContainer;
import com.xq.tmall.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.TimeUnit;

@Slf4j
public class StockSectorTimerJobImpl extends AbstractTimeJob {

    private SimpleTimerJobContainer stockSectorJob;

    public StockSectorTimerJobImpl() {
        name = "每日更新板块数据信息";
    }
    @Override
    public void execute(COMMAND command) throws Exception {

        switch (command){
            case START:
                if (null == stockSectorJob) {
                    log.info("开启更新板块信息更新线程!");
                    StockSectorSpider stockSectorSpider = SpringContextUtil.getBean(StockSectorSpider.class);
                    // 2. 计算初始延迟（到当天16:00的时间差，关键修改！）
                    new Thread(stockSectorSpider, "StockHistoryJob").start();
                    status=STATUS.RUN;
                }
                break;
            case STOP:
                if (null != stockSectorJob) {
                    log.info("关闭更新板块信息更新线程!");
                    stockSectorJob.shutDown();
                    stockSectorJob = null;
                    status=STATUS.STOP;
                }
                break;
        }
    }
    private long calculateInitialDelayTo16PM() {
        // 定义东八区时区
        ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");

        // 获取当前时间（带时区）
        ZonedDateTime now = ZonedDateTime.now(shanghaiZone);

        // 定义目标时间：今天的16:00（修改此处！原为14:00）
        LocalTime targetTime = LocalTime.of(16, 0);
        ZonedDateTime targetToday = ZonedDateTime.of(now.toLocalDate(), targetTime, shanghaiZone);

        // 如果当前时间已过今天的16:00，则目标时间调整为明天16:00
        if (now.isAfter(targetToday)) {
            targetToday = targetToday.plusDays(1);
        }

        // 计算当前时间到目标时间的延迟（毫秒）
        Duration delay = Duration.between(now, targetToday);
        return delay.toMillis();
    }
}
